import React, {useEffect, useRef, useState} from 'react';
import {ActionType, ProColumns} from '@ant-design/pro-table';
import {Demand} from './data.d';
import {modulesUrl} from "@/assets/constant/modulesUrl";
import TableList from "@/assets/components/tableList";
import {dateFormat, hooksSet, modifyColumns, toInt} from "@/assets/utils/utils";
import {list, listForSelect} from "@/assets/service/baseService";
import {useRequest} from 'umi';
import {Badge, Button, Form} from "antd";
import {Link} from "react-router-dom";
import {PlusOutlined} from "@ant-design/icons";
import {getCurrentUser} from "@/pages/sys/UserList/service";
import moment from "moment";
import {dictType} from "@/assets/constant/dictType";
import {map} from "@/pages/sys/DictList/service";
// @ts-ignore
import $ from 'jquery';

const DemandList: React.FC<{}> = (props) => {
  /**
   * type：0、全部需求  1、待办需求  2、流转中需求   3、已完成需求
   */
    // @ts-ignore
  const type = props.match.params.type;

  const [form] = Form.useForm();
  const [searchRef] = Form.useForm();
  const actionRef = useRef<ActionType>();

  /**
   * 当前用户
   */
  const [currentUser, setCurrentUser] = useState<API.CurrentUser>()
  const getCurrentUserRun = async () => {
    const currentUser: API.CurrentUser = await getCurrentUser();
    hooksSet(setCurrentUser, currentUser)
  }
  /**
   * 获取需求类型列表
   */
  useRequest(() => listForSelect(modulesUrl.demandDemandType), {
    onSuccess: (result, params) => {
      hooksSet(setColumns, modifyColumns(columns, "typeId", {fieldProps: {options: result}}));
    }
  })

  /**
   * 获取字典列表
   * @type 字典类型
   */
  const dictMap = useRef();
  useRequest(() => map({type: dictType.DEMAND_STATUS}), {
    onSuccess: (result, params) => {
      dictMap.current = result;
    }
  })

  const [columns, setColumns] = useState<ProColumns<Demand>[]>([
    {
      title: '需求名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
      // @ts-ignore
      // initialValue:localStorage.getItem('demandListSearch') ? JSON.parse(localStorage.getItem('demandListSearch'))?.name : undefined,
      renderText: (text, record) => <Link
        to={"/demand/demand/" + type + (record.status === "1" ? "/edit/" : "/form/") + record.id}>{text}</Link>,
    },
    {
      title: '编号',
      dataIndex: 'code',
      hideInSearch: true,
      hideInForm: true,
      sorter: (a, b) => (toInt(a.code) || 0) - (toInt(b.code) || 0),
    },
    {
      title: '需求发起人',
      dataIndex: 'createByUser.name',
      hideInForm: true,
      // @ts-ignore
      // initialValue:localStorage.getItem('demandListSearch') ? JSON.parse(localStorage.getItem('demandListSearch'))["createByUser.name"] : undefined,
      renderText: (_, record) => record.createByUser?.name,
    },
    {
      title: '需求类型',
      dataIndex: 'typeId',
      valueType: "select",
      // @ts-ignore
      // initialValue:localStorage.getItem('demandListSearch') ? JSON.parse(localStorage.getItem('demandListSearch'))["typeId"] : undefined,
      renderText: (_, record) => record.type?.name,
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      hideInForm: true,
      hideInSearch: true,
      // // @ts-ignore
      // initialValue:JSON.parse(localStorage.getItem('demandListSearch'))["createDateSearch"],
      renderText: (_, record) => dateFormat(record.createDate),
      sorter: (a, b) => (toInt(moment(a.createDate).format("yyyyMMDDHHmmss")) || 0) - (toInt(moment(b.createDate).format("yyyyMMDDHHmmss")) || 0),
    },
    {
      title: '需求状态',
      dataIndex: 'status',
      hideInSearch: true,
      hideInForm: true,
      renderText: (text, record) => {
        let badgeStatus: string[] = ["default", "warning", "processing", "success", "success", "error"]
        // @ts-ignore
        return <Badge status={badgeStatus[text]} text={dictMap.current[text]}/>;
      }
    },
    {
      title: '预计完成时间',
      dataIndex: 'estimateFinishDate',
      hideInForm: true,
      hideInSearch: true,
      renderText: (text) => dateFormat(text),
      sorter: (a, b) => (toInt(moment(a.estimateFinishDate).format("yyyyMMDDHHmmss")) || 0) - (toInt(moment(b.estimateFinishDate).format("yyyyMMDDHHmmss")) || 0),
    },
    {
      title: '当前用户',
      dataIndex: 'nowUserName',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) => record.nowUser?.name + "（" + (record.flowStatusName || "草稿") + "）",
    },
    {
      title: '预计工时（小时）',
      dataIndex: 'estimateWorkingHours',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '预计工时为必填项',
          },
        ],
      },
    },
    {
      title: '实际工时（小时）',
      dataIndex: 'actualWorkingHours',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInTable: true,
      hideInSearch: true,
      valueType: "textarea",
      formItemProps: {
        rules: [
          {
            required: true,
            message: '描述为必填项',
          },
        ],
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createDateSearch',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true
    },
  ]);

  /**
   * 启动加载
   */
  useEffect(() => {
    // 获取当前用户
    getCurrentUserRun()
    actionRef.current?.reload()
  }, [type]);

  return (
    <TableList
      title={"需求列表"}
      isNotCanAdd={currentUser?.roleEnNames?.split(",")?.indexOf("promoter") == -1 || false}
      isNotShowDeleteOption={true}
      addOption={<Button type={"primary"}><Link
        to={"/demand/demand/" + type + "/edit/0"}><PlusOutlined/> 新建</Link></Button>}
      isNotShowOption={true}
      actionRef={actionRef}
      form={form}
      searchRef={searchRef}
      changeColumns={(columns: any) => hooksSet(setColumns, columns)} columns={columns}
      moduleUrl={modulesUrl.demandDemand}
      request={(params: any) => {
        // 存储查询参数到全局
        // if(Object.keys(params).length > 2){
        //   localStorage.setItem('demandListSearch', JSON.stringify(params));
        // }
        return list(modulesUrl.demandDemand, Object.assign({}, params, {"findType": type}))
      }}
      searchOptionRender={({searchText, resetText}: any, {form}: any, dom: any[]) => {
        return [
          <Button onClick={()=>{
            // localStorage.removeItem('demandListSearch')
            window.location.reload()
            // actionRef.current?.reload()
          }}>重 置</Button>
          ,dom[1]
        ];
      }}
    />
  )
}

export default DemandList
